#!/bin/bash

# 物业保洁系统快速测试脚本
# 自动执行基本功能测试

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置
BASE_URL="http://localhost:8080"
FRONTEND_URL="http://localhost:3000"
TIMEOUT=30

# 测试计数
TESTS_PASSED=0
TESTS_FAILED=0
TOTAL_TESTS=0

# 日志函数
log() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')] $1${NC}"
}

error() {
    echo -e "${RED}[$(date '+%H:%M:%S')] ERROR: $1${NC}"
}

warning() {
    echo -e "${YELLOW}[$(date '+%H:%M:%S')] WARNING: $1${NC}"
}

info() {
    echo -e "${BLUE}[$(date '+%H:%M:%S')] INFO: $1${NC}"
}

# 测试结果记录
test_result() {
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✓ $2${NC}"
        TESTS_PASSED=$((TESTS_PASSED + 1))
    else
        echo -e "${RED}✗ $2${NC}"
        TESTS_FAILED=$((TESTS_FAILED + 1))
    fi
}

# 等待服务启动
wait_for_service() {
    local url=$1
    local service=$2
    local max_attempts=30
    local attempt=1
    
    info "等待 $service 服务启动..."
    
    while [ $attempt -le $max_attempts ]; do
        if curl -s --connect-timeout 5 "$url" > /dev/null 2>&1; then
            log "$service 服务已启动"
            return 0
        fi
        
        echo -n "."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    error "$service 服务启动超时"
    return 1
}

# 测试数据库连接
test_database() {
    info "测试数据库连接..."
    
    # 检查MySQL容器
    if docker ps | grep -q "property-mysql"; then
        test_result 0 "MySQL容器运行正常"
    else
        test_result 1 "MySQL容器未运行"
    fi
    
    # 检查Redis容器
    if docker ps | grep -q "property-redis"; then
        test_result 0 "Redis容器运行正常"
    else
        test_result 1 "Redis容器未运行"
    fi
}

# 测试后端API
test_backend_api() {
    info "测试后端API..."
    
    # 健康检查
    if curl -s "$BASE_URL/actuator/health" | grep -q "UP"; then
        test_result 0 "后端健康检查通过"
    else
        test_result 1 "后端健康检查失败"
    fi
    
    # 测试用户API
    local response=$(curl -s -w "%{http_code}" -o /dev/null "$BASE_URL/api/users")
    if [ "$response" = "200" ]; then
        test_result 0 "用户API正常"
    else
        test_result 1 "用户API返回 $response"
    fi
    
    # 测试区域API
    response=$(curl -s -w "%{http_code}" -o /dev/null "$BASE_URL/api/areas")
    if [ "$response" = "200" ]; then
        test_result 0 "区域API正常"
    else
        test_result 1 "区域API返回 $response"
    fi
}

# 测试前端页面
test_frontend() {
    info "测试前端页面..."
    
    # 检查首页
    local response=$(curl -s -w "%{http_code}" -o /dev/null "$FRONTEND_URL")
    if [ "$response" = "200" ]; then
        test_result 0 "前端首页可访问"
    else
        test_result 1 "前端首页返回 $response"
    fi
}

# 测试数据库数据
test_database_data() {
    info "测试数据库数据..."
    
    # 检查用户表
    local user_count=$(docker exec property-mysql-dev mysql -u root -proot123 -e "SELECT COUNT(*) FROM property_cleaning.users;" -s -N 2>/dev/null || echo "0")
    if [ "$user_count" -gt 0 ]; then
        test_result 0 "用户表有数据 ($user_count 条)"
    else
        test_result 1 "用户表无数据"
    fi
    
    # 检查区域表
    local area_count=$(docker exec property-mysql-dev mysql -u root -proot123 -e "SELECT COUNT(*) FROM property_cleaning.areas;" -s -N 2>/dev/null || echo "0")
    if [ "$area_count" -gt 0 ]; then
        test_result 0 "区域表有数据 ($area_count 条)"
    else
        test_result 1 "区域表无数据"
    fi
}

# 测试性能
test_performance() {
    info "测试性能..."
    
    # 测试API响应时间
    local start_time=$(date +%s%N)
    curl -s "$BASE_URL/api/users" > /dev/null
    local end_time=$(date +%s%N)
    local duration=$(( (end_time - start_time) / 1000000 ))
    
    if [ $duration -lt 1000 ]; then
        test_result 0 "API响应时间: ${duration}ms"
    else
        test_result 1 "API响应时间过慢: ${duration}ms"
    fi
}

# 测试功能完整性
test_functionality() {
    info "测试功能完整性..."
    
    # 测试用户注册
    local test_user='{"username":"test_user","password":"test123","email":"test@example.com","phone":"1234567890","role":"USER"}'
    local response=$(curl -s -w "%{http_code}" -o /dev/null \
        -X POST -H "Content-Type: application/json" \
        -d "$test_user" "$BASE_URL/api/users/register")
    
    if [ "$response" = "201" ]; then
        test_result 0 "用户注册功能正常"
    else
        test_result 1 "用户注册失败 ($response)"
    fi
    
    # 测试区域创建
    local test_area='{"name":"测试区域","description":"测试描述","address":"测试地址","manager":"测试管理员","phone":"1234567890"}'
    response=$(curl -s -w "%{http_code}" -o /dev/null \
        -X POST -H "Content-Type: application/json" \
        -d "$test_area" "$BASE_URL/api/areas")
    
    if [ "$response" = "201" ]; then
        test_result 0 "区域创建功能正常"
    else
        test_result 1 "区域创建失败 ($response)"
    fi
}

# 清理测试数据
cleanup_test_data() {
    info "清理测试数据..."
    
    # 删除测试用户
    docker exec property-mysql-dev mysql -u root -proot123 -e "DELETE FROM property_cleaning.users WHERE username='test_user';" 2>/dev/null || true
    
    # 删除测试区域
    docker exec property-mysql-dev mysql -u root -proot123 -e "DELETE FROM property_cleaning.areas WHERE name='测试区域';" 2>/dev/null || true
    
    log "测试数据已清理"
}

# 生成测试报告
generate_report() {
    echo
    echo "===================="
    echo "测试报告"
    echo "===================="
    echo "总测试数: $TOTAL_TESTS"
    echo "通过: $TESTS_PASSED"
    echo "失败: $TESTS_FAILED"
    echo "成功率: $(( (TESTS_PASSED * 100) / TOTAL_TESTS ))%"
    echo
    
    if [ $TESTS_FAILED -eq 0 ]; then
        log "所有测试通过！系统运行正常"
    else
        warning "部分测试失败，请检查日志"
    fi
}

# 主函数
main() {
    echo "物业保洁系统快速测试工具"
    echo "========================"
    echo
    
    # 检查参数
    if [ "$1" = "--help" ]; then
        echo "用法: $0 [选项]"
        echo
        echo "选项:"
        echo "  --help     显示帮助信息"
        echo "  --skip-wait 跳过服务启动等待"
        echo
        exit 0
    fi
    
    # 等待服务启动（除非跳过）
    if [ "$1" != "--skip-wait" ]; then
        wait_for_service "$BASE_URL/actuator/health" "后端"
        wait_for_service "$FRONTEND_URL" "前端"
    fi
    
    # 执行测试
    test_database
    test_backend_api
    test_frontend
    test_database_data
    test_performance
    test_functionality
    
    # 清理测试数据
    cleanup_test_data
    
    # 生成报告
    generate_report
    
    # 提供下一步建议
    echo
    echo "下一步建议:"
    echo "1. 访问前端: $FRONTEND_URL"
    echo "2. 查看后端文档: $BASE_URL/swagger-ui.html"
    echo "3. 检查监控: $BASE_URL/actuator"
    echo
}

# 执行主函数
main "$@"